<?php

namespace backend\controllers;

use backend\models\UploadForm;
use Yii;
use backend\models\Doctor;
use backend\models\DoctorSearch;
use backend\controllers;
use yii\imagine\Image;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * DoctorController implements the CRUD actions for Doctor model.
 */
class DoctorController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Doctor models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DoctorSearch();
        $doctorData = $searchModel->mySearch(Yii::$app->request->queryParams);
        //$dataProvider = $searchModel->search(['DoctorSearch' => [ 'status' => 1]]); 这里是直接帅选数据的格式
        //$model = $dataProvider->models;

        return $this->render('index', [
            'doctorData' => $doctorData,
        ]);
    }

    /**
     * Displays a single Doctor model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Doctor model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Doctor();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Doctor model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate()
    {
        $id = Yii::$app->request->get('id');
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Doctor model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * 删除医生信息
     * @return false|int
     * @throws NotFoundHttpException
     * @throws \Exception
     */
    public function actionDeleteDoctor()
    {
        $id = Yii::$app->request->post('id');
        $re = $this->findModel($id)->delete();

        return $re ? 1 : 0;
    }
    /**
     * Finds the Doctor model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Doctor the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Doctor::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 上传头像图片操作
     */
    public function actionUpload()
    {
        $uploadDir = '/uploads/'; //文件上传目录
        $fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // 允许上传文件格式
        $verifyToken = md5('unique_salt' . $_POST['timestamp']);

        if (!empty($_FILES) && $_POST['token'] == $verifyToken)
        {
            //上传目录选择
            if($_POST['mulu'])
            {
                $uploadDir = $uploadDir.$_POST['mulu'].'/';
            }
            //文件夹不存在生成文件夹
            if(!is_dir($dirname = $uploadDir))
            {
                mkdir($dirname, 0777, true);
                chmod($dirname, 0777);//这个必须有 而且上级目录也得属于 www-data 这个用户
            }
            $tempFile   = $_FILES['Filedata']['tmp_name'];
            $moverDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
            // 上传移动文件
            $fileParts = pathinfo($_FILES['Filedata']['name']);
            $filename = "temp_" . time() . rand(1,10000);
            $targetFile = $moverDir . $filename. '.'. $fileParts['extension']; //防止重复重新命名一下上传文件
            $fileDir = $uploadDir . $filename. '.'. $fileParts['extension']; //防止重复重新命名一下上传文件
            if (in_array(strtolower($fileParts['extension']), $fileTypes))
            {
                // Save the file
                move_uploaded_file($tempFile, $targetFile);
                $data = [
                    'status' => 1,
                    'imgUrl' => $fileDir
                ];
                echo json_encode($data);
            } else
            {
                // The file type wasn't allowed
                echo 'Invalid file type.';
            }
        }
    }

    /**
     * 裁剪图片
     */
    public function actionCrop()
    {
        $x1 = $id = Yii::$app->request->post('x1');
        $x2 = $id = Yii::$app->request->post('x2');
        $y1 = $id = Yii::$app->request->post('y1');
        $y2 = $id = Yii::$app->request->post('y2');
        $imgUrl = $id = Yii::$app->request->post('imgUrl');
        $width = $x2 - $x1;
        $height = $y2 - $y1;
        $file = $_SERVER['DOCUMENT_ROOT'].$imgUrl;
        $ext = substr(strrchr($file, '.'), 1);
        $saveFile = $filename = "uploads/doctor/head_" . time() . rand(1,10000).'.'.$ext;
        Image::crop($file,$width,$height,[$x1,$y2])->save($saveFile,['quality' => 80]);

        $data = [
            'status' => 1,
            'imgUrl' => '/'.$saveFile
        ];
        echo json_encode($data);
    }
}
